﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartyOcr
{
    /// <summary>
    /// 特征数据加载器
    /// xue8000@gmail.com
    /// xueliang @2012-11-11
    /// </summary>
    public static class CharactoristicLoader
    {
        static readonly string CharactoristicPath = Environment.CurrentDirectory + "/SmartyOcr.Charactoristic/";
        public static  LinkedList<KeyValuePair<string, string>> Charactoristic {private set; get; }
        static CharactoristicLoader() {
            #region//加载特征数据
            #region//判断特征数据所在目录是否存在
            if (!System.IO.Directory.Exists(CharactoristicPath))
            {
                try
                {
                    System.IO.Directory.CreateDirectory(CharactoristicPath);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.Assert(false,
                                string.Format(@"建立{0}文件夹时,发生了异常{1}:{2}",
                                CharactoristicPath,
                                Environment.NewLine,
                                e.Message + Environment.NewLine + e.StackTrace));
                }
            }
            #endregion
            #region//加载已学习的特征数据
            Charactoristic = new LinkedList<KeyValuePair<string, string>>();
            var resources = System.IO.Directory.GetFiles(CharactoristicPath, "*.rsc");
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(Charactoristic.GetType());
            foreach (var rsc in resources)
            {
                using (var reader = new System.IO.StreamReader(rsc))
                {
                    var data = serializer.ReadObject(reader.BaseStream) as LinkedList<KeyValuePair<string, string>>;
                    foreach (var kv in data)
                    {
                        if(Charactoristic.Where(i=>i.Value == kv.Value).Count()>0)
                        {
                            continue;
                        }
                        else
                        {
                            Charactoristic.AddFirst(new KeyValuePair<string,string>(kv.Key, kv.Value));
                        }
                    }
                }
            }
            #endregion
            #endregion
        }
    }
}
